#include<iostream>
#include<unistd.h>
#include<pthread.h>
using namespace std;

int tickets = 200;//临界资源
pthread_mutex_t lock;//lock需要被所有的线程先看到，本质也是一种临界资源

void* Routine(void* args)
{
	cout <<"before"<<endl;
	//pthread_mutex_lock(&lock);
	while(1)
	{
		pthread_mutex_lock(&lock);
		cout <<"after" << endl;
		if(tickets > 0)
		{
			usleep(30000);
			printf("0x%x: get a ticket : %d\n",(int)pthread_self(),tickets);
			tickets--;
			pthread_mutex_unlock(&lock);
			usleep(1);
		}
		else
		{
			pthread_mutex_unlock(&lock);
			break;
		}
	}
	printf("0x%x: quit, tickets: %d\n",(int)pthread_self(),tickets);
	return nullptr;
}
int main()
{
	pthread_mutex_init(&lock,NULL);
#define NUM 5
	pthread_t nums[NUM];
	for(int i = 0; i < NUM; ++i)
	{
		pthread_create(nums+i,nullptr,Routine,nullptr);
	}
	for(int i = 0; i < NUM; ++i)
	{
		pthread_join(nums[i],nullptr);
	}
	pthread_mutex_destroy(&lock);
	return 0;
}
